package com.flyduck.security.config;

import com.flyduck.security.util.JwtTokenUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p></p>
 *
 * @author flyduck 2021/7/7
 * @version V1.0
 * @modificationHistory=========================逻辑或功能性重大变更记录
 * @modify by user: flyduck 2021/7/7
 * @modify by reason:{方法名}:{原因}
 **/
public class AppAuthorizationFilter extends BasicAuthenticationFilter {

    public AppAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        Authentication authentication = getAuthentication(request);

        if (authentication == null) {
            chain.doFilter(request, response);
            return;
        }

        SecurityContextHolder.getContext().setAuthentication(authentication);
        chain.doFilter(request, response);
    }

    private Authentication getAuthentication(HttpServletRequest request) {
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);

        if (!StringUtils.isEmpty(token)) {
            token = token.replace(JwtTokenUtil.TOKEN_PREFIX, "");
            String userName = JwtTokenUtil.getUserName(token);
            List<String> tokenAuthorities = JwtTokenUtil.getAuthorities(token);
            Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
            for (String authority : tokenAuthorities) {
                authorities.add(new SimpleGrantedAuthority(authority));
            }
            return new UsernamePasswordAuthenticationToken(userName, token, authorities);
        }
        return null;
    }
}
